package naga.x.platform2.channel.jg;

import java.util.Map;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import naga.x.platform2.app.Channel;
import naga.x.platform2.app.model.GameServer;
import naga.x.platform2.app.model.Recharge;
import naga.x.platform2.app.model.RechargeTemplate;
import naga.x.platform2.app.support.GameServerSupport;
import naga.x.platform2.app.support.RechargeSupport;
import naga.x.platform2.channel.jg.support.JGApi;
import naga.x.platform2.channel.jg.support.JGConfig;
import naga.x.platform2.channel.s399.support.S399Api.Code;
import naga.x.platform2.channel.s399.support.S399Api.PayInfo;
import naga.x.platform2.support.RequestPath;
import naga.x.platform2.utils.HttpUtils;
import naga.x.platform2.utils.NumberUtils;
import naga.x.platform2.utils.PlatformUtils;

/**
 * 9G
 * @author yang.li
 *
 */
@Controller
public class JGController {

	@Autowired
	private JGConfig config;
	@Autowired
	private JGApi api;
	@Autowired
	private RechargeSupport support;
	@Autowired
	private GameServerSupport gameServers;
	
	private static Channel channel = Channel.JG;
	
	public static final Logger LOG = LoggerFactory.getLogger(JGController.class);
	
	@RequestMapping(path = RequestPath.JG_LOGIN)
	public String login(String gameid, String channel, String token) {
		String url = config.getUserInfoUrl9G() + "?gameid=" + config.getGameId() + "&token=" + token;
		try {
			JSONObject res = JSON.parseObject(HttpUtils.get(url));
			res.put("channel", channel);
			res.put("token", token);
			return api.createLoginRedirectUrl(res);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		JSONObject error = new JSONObject(2);
		error.put("errcode", -1);
		error.put("errmsg", "token error~");
		return api.createLoginRedirectUrl(error);
	}
	
	@RequestMapping(path = RequestPath.JG_PAY, produces = "application/json; charset=UTF-8")
	@ResponseBody
	public Object pay(Integer sid, Long pid, Integer product) {
		GameServer gs = gameServers.get(sid);
		if (gs == null) {
			return api.newError(Code.SERVER_NOT_FOUND);
		}
		if (pid == null) {
			return api.newError(Code.PLAYER_ID_ERROR);
		}
		RechargeTemplate template = support.getTemplate(product);
		if (template == null) {
			return api.newError(Code.RECHARGE_PRODUCT_NOT_FOUND);
		}
		return api.newOrder(sid, pid, template);
	}
	
	@RequestMapping(path = RequestPath.JG_PAY_CALLBACK)
	@ResponseBody
	public String payCallback(String orderid, Integer money/*分*/, Integer status, String sign, String attach) {
		if (orderid == null || money == null || status == null || sign == null) {
			LOG.info("[9G PAY ERR]ORDERID[{}]MONEY[{}]STATUS[{}]SIGN[{}]ATTACH[{}]CAUSE[PARAMSERR]",
									orderid, money, status, sign, attach);
			return "PARAMSERR";
		}
		String s = api.makePayCallbackSign(orderid, money, status);
		if (!s.equals(sign)) {
			LOG.info("[9G PAY ERR]ORDERID[{}]MONEY[{}]STATUS[{}]SIGN[{}]ATTACH[{}]SIGN2[{}]CAUSE[SIGNERR]",
					orderid, money, status, sign, attach, s);
			return "SIGNERR";
		}
		if (status != 1) {
			LOG.info("[9G PAY ERR]ORDERID[{}]MONEY[{}]STATUS[{}]SIGN[{}]ATTACH[{}]CAUSE[STATUSERR]",
					orderid, money, status, sign, attach);
			return "OK";
		}
		PayInfo pay = JGApi.parsePay(attach);
		GameServer gs = gameServers.get(pay.serverId);
		if (gs == null) {
			LOG.info("[9G PAY ERR]ORDERID[{}]MONEY[{}]STATUS[{}]SIGN[{}]ATTACH[{}]CAUSE[GSERR]",
					orderid, money, status, sign, attach);
			return "GSERR";
		}
		RechargeTemplate product = support.getTemplate(pay.productId);
		if (product == null) {
			LOG.info("[9G PAY ERR]ORDERID[{}]MONEY[{}]STATUS[{}]SIGN[{}]ATTACH[{}]CAUSE[PRODUCTERR]",
					orderid, money, status, sign, attach);
			return "PRODUCTERR";
		}
		if (money / 100 < product.getPrice()) {
			LOG.info("[9G PAY ERR]ORDERID[{}]MONEY[{}]STATUS[{}]SIGN[{}]ATTACH[{}]CAUSE[MONEYERR]",
					orderid, money, status, sign, attach);
			return "MONEYERR";
		}
		Recharge entity = new Recharge(channel.prefix + orderid, pay.playerId, pay.serverId, money / 100, product.getStone(), product.getId(), channel.name);
		boolean succ = support.offer(entity);
		LOG.info("[9G PAY SUCC]ORDERID[{}]MONEY[{}]STATUS[{}]SIGN[{}]ATTACH[{}]SUCC[{}]",
				orderid, money, status, sign, attach, succ ? 1 : 0);
		return "OK";
	}
	
	@RequestMapping(path = RequestPath.JG_SUBSCRIBE)
	@ResponseBody
	public String subscribe(String uid, String gameid, String server_id, String sign) {
//		sign = MD5.encode(uid + "" + gameid + "" + server_id + "" + spkey)
//		1: 发放成功
//		0: 已发放过奖励忽略
//		-1: 发放失败
		String s = api.makeSign(uid, gameid, server_id);
		if (!s.equals(sign)) {
			return "-1";
		}
		int serverId = NumberUtils.parseInt(server_id);
		GameServer gs = gameServers.get(serverId);
		if (gs == null) {
			return "-1";
		}
		String url = gs.getGMUrl();
		Map<String, String> params = new TreeMap<String, String>();
		params.put("cmd", "9g_subscribe_cb");
		params.put("data", uid);
		params.put("sign", PlatformUtils.makeSign(gs, params));
		String res = HttpUtils.post(url, params);
		int code = NumberUtils.parseInt(res, -1);
		return String.valueOf(code);
	}
	
}
